﻿using Dapper;
using System;
using BCEntity.CRM.IndustryCategory;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using BCCommon;

namespace BCData.CRM.IndustryCategory
{
    /// <summary>
    /// 行业类别
    /// </summary>
    public class IndustryCategoryData : IIndustryCategoryData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM industrycategory";
        private const string QUERY = @"SELECT IndustryCategoryId,IndustryCategoryName,ParentIndustryCategoryId,Level,IndustryCategoryTreeCode,CreateTime,UpdateTime FROM industrycategory";
        public IndustryCategoryData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }
        #region 检查行业类别是否存在
        public async Task<bool> Exists(long industryCategoryId)
        {
            string sql = string.Format(@"{0} WHERE IndustryCategoryId=?IndustryCategoryId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?IndustryCategoryId", industryCategoryId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 添加行业类别
        public async Task<IndustryCategoryEntity> Add(IndustryCategoryEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("industrycategory", new string[] { "IndustryCategoryName", "Level", "IndustryCategoryTreeCode", "UpdateTime" });
            sql = string.Format("{0} {1} WHERE IndustryCategoryId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?IndustryCategoryName", entity.IndustryCategoryName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?Level", entity.Level, DbType.Int32, size: 11);
            parameters.Add("?IndustryCategoryTreeCode", entity.IndustryCategoryTreeCode?.Trim(), DbType.AnsiString, size: 1000);
            parameters.Add("?UpdateTime", entity.UpdateTime, DbType.DateTime);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<IndustryCategoryEntity>(sql, parameters, databaseContext.Transaction);

        }
        #endregion

        #region 修改行业类别
        public async Task<IndustryCategoryEntity> Update(IndustryCategoryEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("industrycategory", new string[] { "IndustryCategoryName", "ParentIndustryCategoryId", "Level", "IndustryCategoryTreeCode", "UpdateTime" }, new string[] { "IndustryCategoryId" });
            sql = string.Format("{0} {1} WHERE IndustryCategoryId=?IndustryCategoryId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?IndustryCategoryId", entity.IndustryCategoryId, DbType.Int64, size: 20);
            parameters.Add("?IndustryCategoryName", entity.IndustryCategoryName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?ParentIndustryCategoryId", entity.ParentIndustryCategoryId, DbType.Int64, size: 20);
            parameters.Add("?Level", entity.Level, DbType.Int32, size: 11);
            parameters.Add("?IndustryCategoryTreeCode", entity.IndustryCategoryTreeCode?.Trim(), DbType.AnsiString, size: 1000);
            parameters.Add("?UpdateTime", entity.UpdateTime, DbType.DateTime);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<IndustryCategoryEntity>(sql, parameters, databaseContext.Transaction);
        }
        #endregion

        #region 删除行业类别
        public async Task<bool> Delete(long industryCategoryId)
        {
            string sql = @"DELETE FROM industrycategory WHERE IndustryCategoryId=?IndustryCategoryId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?IndustryCategoryId", industryCategoryId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 获取行业类别
        public async Task<IndustryCategoryEntity> GetEntity(long industryCategoryId)
        {
            string sql = string.Format(@"{0} WHERE IndustryCategoryId=?IndustryCategoryId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?IndustryCategoryId", industryCategoryId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<IndustryCategoryEntity>(sql, parameters);
        }
        #endregion

        #region 获取行业类别列表
        public async Task<IEnumerable<IndustryCategoryEntity>> GetList()
        {
            return await this.databaseContext.Slave.QueryAsync<IndustryCategoryEntity>(QUERY);
        }
        #endregion

        #region 获取行业类别分页
        public async Task<(IEnumerable<IndustryCategoryEntity>, int)> Query(DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();

            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM industrycategory {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
            return await this.databaseContext.Slave.QueryMultipleAsync<IndustryCategoryEntity, int>(sql, parameters);
        }
        #endregion
    }
}



